/* 
 * shamefully copy from AnFetion.
 * more see: http://code.google.com/p/anfetion/
 */
package person.bangbang.im.Androidgin.Fetion;



import person.bangbang.im.Androidgin.Fetion.TcpSendAndReceive.IPackageReceivedHandler;
import person.bangbang.im.Androidgin.Util.Log;


public abstract class SIPCBase extends FetionBase {
    protected static final String SIPC_COMMON_HEADER = "S fetion.com.cn SIP-C/2.0"; 
    protected SerialManager serialManager;
    protected TcpSendAndReceive connection;
    protected final static String SIPC_RESPONSE_CODE_INVITE_TRYING = "100";
    protected final static String SIPC_RESPONSE_CODE_OK = "200";
    protected final static String SIPC_RESPONSE_CODE_NOTEXIST = "404";
    protected final static String SIPC_RESPONSE_CODE_TEMPORARILYUNAVALIABLE = "480";
    protected final static String SIPC_RESPONSE_CODE_SENDSMS_OK = "280";
    protected final static String SIPC_RESPONSE_CODE_UNAUTHRIZED = "401";
    protected final static String SIPC_RESPONSE_CODE_NOSUBSCRIPTION = "522";

    public SIPCBase(SerialManager serialManager, TcpSendAndReceive connection) {
        this.serialManager = serialManager;
        this.connection = connection;
        Log.d("SIPCBase", "in SIPCBase constructor");
    }

    protected boolean SendAndReceiveResponse(final FetionSIPC sipc) {
        IPackageReceivedHandler handler = new IPackageReceivedHandler() {

            public boolean received(FetionSIPC receivedsipc) {
                try {
                    if (receivedsipc.isResponse() && sipc.GetQ().equals(receivedsipc.GetQ())) {
                        sipc.SetResponse(receivedsipc);
                        FrameWork.synchronizednotify(this);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }

        };
        connection.addPackageReceivedQueue(handler);
        connection.SendSIPC(sipc);
        if (sipc.response == null) {
            // System.out.println("wait " + sipc.response);
            FrameWork.synchronizedwait(handler, 10000);
            // System.out.println("ret " + sipc.response);
        }
        connection.removePackageReceivedQueue(handler);
        if (sipc.response != null) return true;
        else return false;
    }
}
